//
//  FaQiuTrainController.m
//  CoolTennisBall
//
//  Created by Coollang on 16/7/20.
//  Copyright © 2016年 CoolLang. All rights reserved.
//

#import "FaQiuTrainController.h"
#import "MTPanelChart.h"
#import "RssiView.h"
#import "ArcView.h"
#import "MTScatterChart.h"
#import <UICountingLabel/UICountingLabel.h>
#import "ChartItem.h"
#import "RealTimeTrainModel.h"
#import "NSString+Extension.h"
#import "UIView+Frame.h"

@interface FaQiuTrainController ()


/***  顶部实时  **/
@property (weak, nonatomic) IBOutlet MTPanelChart *panelChartView;
@property (weak, nonatomic) IBOutlet UIView *swingSpeedView;
@property (weak, nonatomic) IBOutlet UIView *trunAngleView;

@property (weak, nonatomic) IBOutlet UICountingLabel *swingSpeedLabel;
@property (weak, nonatomic) IBOutlet UICountingLabel *trunAngleLabel;
@property (weak, nonatomic) IBOutlet UICountingLabel *ForecastSpeedLabel;

/***  中间趋势图  **/
@property (weak, nonatomic) IBOutlet UILabel *averageSpeedLabel;
/** 散点图 */
@property (strong, nonatomic)IBOutlet MTScatterChart *scatterView;

/***  底部视图  **/
@property (weak, nonatomic) IBOutlet UILabel *completeNumberLabel;

@property (nonatomic, strong) NSMutableArray *chartItemArr;

@property (nonatomic, strong)NSMutableArray *maxSpeedArr;

// 达标量
@property (nonatomic, assign)NSInteger reachStandard;
@property (nonatomic, assign)CGFloat currentProgress; // 转盘的当前进度

/** 国际化 */
@property (weak, nonatomic) IBOutlet UILabel *avgLabel;
@property (weak, nonatomic) IBOutlet UILabel *avgKmUnitLab;
@property (weak, nonatomic) IBOutlet UILabel *forecastSpeedLab;
@property (weak, nonatomic) IBOutlet UILabel *angleLab;
@property (weak, nonatomic) IBOutlet UILabel *swingSpeedLab;
@property (weak, nonatomic) IBOutlet UILabel *ballSpeedLab;// 球速趋势
@property (weak, nonatomic) IBOutlet UILabel *ballSpeedKmLab;


@end

@implementation FaQiuTrainController {
    
    BOOL _endTrain;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureLocalization];
    [self configuerSetUpUI];
    
    self.swingSpeedLabel.format = @"%d";
    self.swingSpeedLabel.method = UILabelCountingMethodEaseInOut;
    
    self.trunAngleLabel.format = @"%d";
    self.trunAngleLabel.method = UILabelCountingMethodEaseInOut;
    
    self.ForecastSpeedLabel.format = @"%d";
    self.ForecastSpeedLabel.method = UILabelCountingMethodEaseInOut;
    
    _endTrain = YES;
    
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    [self.swingSpeedView layoutIfNeeded];
    [self.trunAngleView layoutIfNeeded];
    

    CGFloat redius = MIN(self.swingSpeedView.bounds.size.width, self.swingSpeedView.bounds.size.height) * 0.5;
    
    self.swingSpeedView.layer.cornerRadius = redius;
    self.trunAngleView.layer.cornerRadius = redius;
    self.swingSpeedView.layer.masksToBounds = YES;
    self.trunAngleView.layer.masksToBounds = YES;
    
    self.swingSpeedView.layer.borderWidth = 1;
    self.swingSpeedView.layer.borderColor = [UIColor colorWithHex:0xff8560 alpha:0.2].CGColor;
    self.trunAngleView.layer.borderWidth = 1;
    self.trunAngleView.layer.borderColor = [UIColor colorWithHex:0xff8560 alpha:0.2].CGColor;
    
    self.panelChartView.radius = self.panelChartView.bounds.size.width * 0.5 - 10;
    
    [self.scatterView layoutIfNeeded];
    [self.scatterView setDefaultValues];
    
    [self.scatterView updateTargetSpeed:self.targetModel.faQiuTargetSpeed withTextString:@"目标球速"];
    
    [self.scatterView drawChart];
    
}

- (void)configureLocalization {
    YFLanguage currentLanguage = [NSBundle currentLangeuage];
    if (currentLanguage != kLanguageChineseSimple) {
        self.avgLabel.text = NSLocalizedString(@"Avg", nil);
        self.avgKmUnitLab.text = @"(km/h)";
        self.forecastSpeedLab.text = NSLocalizedString(@"Prediction\nBall Speed", nil);
        self.ballSpeedKmLab.text =[NSString stringWithFormat:@"%@(km/h)",NSLocalizedString(@"Ball Speed", nil)];
    }
    
    self.swingSpeedLab.text = NSLocalizedString(@"RealTime.SwingSpeed", nil);
    self.angleLab.text = NSLocalizedString(@"Racket Angle", nil);
    self.ballSpeedLab.text = NSLocalizedString(@"Shots Distribution", nil);
    NSString *completeStr = NSLocalizedString(@"RealTime.Completed", nil);
    
    self.completeNumberLabel.text = [NSString stringWithFormat:@"%@:%zd/%zd",completeStr,0, 0];
    
    if (kYFScreenWidth >= 375) {
        self.panelChartView.bounds = CGRectMake(0, 0, kAutoWid(210), kAutoHei(210));
    }
}

- (void)endTrain:(BOOL)isend {
    _endTrain = isend;
    
    if (_endTrain) {
        [self.chartItemArr removeAllObjects];
        [self.maxSpeedArr removeAllObjects];
        //设置平均值
        [self calculateAverageValue];
        [self.scatterView updateScatterDotLayer];
        self.reachStandard = 0;
        self.trainTimeLabel.text = [NSString stringWithTrainTime:0];
    }else {
        
    }
}

//- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//    [self.panelChartView updateProgress:0 endProgress:(arc4random_uniform(101) / 100.0)];
//}

- (void)setChartItem:(ChartItem *)chartItem {
    _chartItem = chartItem;

    if (chartItem.poseType == SportPoseTypeFaQiu || chartItem.poseType == SportPoseTypeKouSha) {
        
        CGFloat speed = [chartItem.maxSpeed floatValue];
        CGFloat arc = [chartItem.arc floatValue];
        
        [self.swingSpeedLabel countFrom:0 to:speed withDuration:1.0f];
        [self.trunAngleLabel countFrom:0 to:arc withDuration:1.0f];
        
        self.swingSpeedLabel.text = chartItem.maxSpeed;
        self.trunAngleLabel.text = chartItem.arc;
        
        CGFloat forecastSpeed = chartItem.forecastSpeed;
        
        CGFloat value = forecastSpeed / 200;
        [self.ForecastSpeedLabel countFrom:0 to:(NSInteger)roundf(forecastSpeed) * 1.0 withDuration:1.0f];
        value = value > 1.0 ? 1.0:value;
        [self.panelChartView updateProgress:self.currentProgress endProgress:value];
        self.currentProgress = value;
        if (!_endTrain) {
             NSInteger speed = (NSInteger)roundf(forecastSpeed);
            [self.maxSpeedArr addObject:@(speed)];
            [self.chartItemArr addObject:chartItem];
            self.scatterView.dotItems = self.maxSpeedArr;
            
            [self.scatterView updateScatterDotLayer];
            [self calculateAverageValue];
            if (speed >= self.targetModel.faQiuTargetSpeed) {
                self.reachStandard++;
            }
            
            NSString *completeStr = NSLocalizedString(@"RealTime.Completed", nil);

            self.completeNumberLabel.text = [NSString stringWithFormat:@"%@:%zd/%zd",completeStr,self.reachStandard, self.chartItemArr.count];
            
        }
        
    }
    
}

- (void)configuerSetUpUI {
    self.swingSpeedView.backgroundColor = [UIColor clearColor];
    self.trunAngleView.backgroundColor = [UIColor clearColor];
    self.panelChartView.backgroundColor = [UIColor clearColor];
    
    self.panelChartView.isShowTick = YES;
    self.panelChartView.isShowtickString = YES;
    self.panelChartView.stokeColor = [UIColor colorWithHex:0xf3f3f3];
    self.panelChartView.borderWidth = 10;
    self.panelChartView.tickStrs = @[@(200),@(180),@(160),@(140),@(120),@(100),@(80),@(60),@(40),@(20),@(0)];
    self.panelChartView.startAngle = (-M_PI * 7)/6;
    self.panelChartView.endAngle = (M_PI)/6;
    self.panelChartView.tickLineHeight = 6;
    self.panelChartView.tickStringBackGroundColor = [UIColor colorWithHex:0x8d8c90 alpha:0.8];
    
    self.panelChartView.tickLineColor = [UIColor colorWithHex:0x8d8c90 alpha:0.5];
    // 设置散点图参数
    self.scatterView.yTitleArray = @[@0, @20, @40, @60, @80, @100, @120, @140, @160, @180, @200];

}

- (void)setTargetModel:(RealTimeTrainModel *)targetModel {
    _targetModel = targetModel;
    
    [self.scatterView updateTargetSpeed:targetModel.faQiuTargetSpeed withTextString:@"目标球速"];
    // 立即更新完成数据的量
    [self UpdateReachStandard];
}
/**立即更新完成数据的量 */
- (void)UpdateReachStandard {
    
    __block NSInteger reachNumber = 0;
    
    [self.maxSpeedArr enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (obj.floatValue >= self.scatterView.targetSpeed) {
            reachNumber++;
        }
    }];

    self.reachStandard = reachNumber;
}

/**
 *  设置平均值
 */
- (void)calculateAverageValue {
    
     __block CGFloat totalCount = 0;
    
    [self.maxSpeedArr enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        totalCount += obj.floatValue;
        
    }];
    if (self.maxSpeedArr.count > 0) {
        self.averageSpeedLabel.text = [NSString stringWithFormat:@"%0.f",totalCount / self.maxSpeedArr.count];
    }else {
        self.averageSpeedLabel.text = @"0";
    }

}


- (NSMutableArray *)chartItemArr {
    if (_chartItemArr == nil) {
        _chartItemArr = [NSMutableArray array];
    }
    return _chartItemArr;
}

- (NSMutableArray *)maxSpeedArr {
    if (_maxSpeedArr == nil) {
        _maxSpeedArr = [NSMutableArray array];
    }
    return _maxSpeedArr;
}

@end


